#! /bin/bash -e

_BASE_DIR=$(dirname $(realpath $0))

APP_DIR=$(realpath ${_BASE_DIR}/../env)
SRC_DIR=${APP_DIR}/src

TARGET="openresty-1.27.1.2"

prompt() {
    echo -e "\033[35;1m$*\033[0m"
}

download() {
    prompt "[cd]"
    cd ${SRC_DIR}
    pwd

    prompt "[download] ${TARGET}"
    curl -O https://openresty.org/download/${TARGET}.tar.gz

    prompt "[tar]"
    tar xf ${TARGET}.tar.gz
    echo "tar [ok]"
}

config_classic() {
    prompt "[cd]"
    cd ${SRC_DIR}/${TARGET}
    pwd

    prompt "[config]"
    ./configure \
        --prefix=${APP_DIR} \
        --with-luajit \
        --with-http_ssl_module \
        --with-http_stub_status_module \
        --with-http_realip_module \
        --with-http_gzip_static_module \
        --with-pcre-jit \
        --with-http_v2_module \
        --with-stream \
        --with-stream_ssl_module

    echo
}

build() {
    prompt "[cd]"
    cd ${SRC_DIR}/${TARGET}
    pwd

    prompt "[build]"
    make -j`nproc`

    prompt "[install]"
    make install
}

main() {
    mkdir -p ${SRC_DIR} ${APP_DIR}

    download
    config_classic
    build
}

main
